// SPDX-License-Identifier: GPL-2.0-or-later
/*
 *   Copyright (C) 2019 Samsung Electronics Co., Ltd.
 */

#include <linux/list.h>
#include <linux/mm.h>
#include <linux/slab.h>
#include <linux/workqueue.h>
#include <linux/cpu.h>
#if defined(CONFIG_ARM)
#include <asm/cputype.h>
#endif
#include "server.h"
#include "connection.h"
#include "ksmbd_work.h"
#include "mgmt/ksmbd_ida.h"

static struct kmem_cache *work_cache;
static struct workqueue_struct *ksmbd_wq;
static bool is_cortex_a9;

struct ksmbd_work *ksmbd_alloc_work_struct(void)
{
	struct ksmbd_work *work = kmem_cache_zalloc(work_cache, GFP_KERNEL);

	if (work) {
		work->compound_fid = KSMBD_NO_FID;
		work->compound_pfid = KSMBD_NO_FID;
		INIT_LIST_HEAD(&work->request_entry);
		INIT_LIST_HEAD(&work->async_request_entry);
		INIT_LIST_HEAD(&work->fp_entry);
		INIT_LIST_HEAD(&work->interim_entry);
	}
	return work;
}

void ksmbd_free_work_struct(struct ksmbd_work *work)
{
	WARN_ON(work->saved_cred != NULL);

	kvfree(work->response_buf);

	if (work->aux_payload_buf != NULL)
		kvfree(work->aux_payload_buf);

	if (work->pipe_file != NULL)
		filp_close(work->pipe_file, NULL);

	kfree(work->tr_buf);
	kvfree(work->request_buf);
	if (work->async_id)
		ksmbd_release_id(&work->conn->async_ida, work->async_id);
	kmem_cache_free(work_cache, work);
}

void ksmbd_work_pool_destroy(void)
{
	kmem_cache_destroy(work_cache);
}

int ksmbd_work_pool_init(void)
{
#if defined(CONFIG_ARM)
	is_cortex_a9 = (read_cpuid_part() == ARM_CPU_PART_CORTEX_A9);
#endif
	work_cache = kmem_cache_create("ksmbd_work_cache",
				       sizeof(struct ksmbd_work), 0,
				       SLAB_HWCACHE_ALIGN, NULL);
	if (!work_cache)
		return -ENOMEM;
	return 0;
}

int ksmbd_workqueue_init(void)
{
	struct workqueue_attrs *attrs;

	if (is_cortex_a9)
		ksmbd_wq = alloc_workqueue("ksmbd-io", WQ_MEM_RECLAIM, 0);
	else
		ksmbd_wq = alloc_workqueue("ksmbd-io", WQ_MEM_RECLAIM | WQ_UNBOUND, 0);

	if (!ksmbd_wq)
		return -ENOMEM;

	attrs = alloc_workqueue_attrs();
	if (!attrs) {
		destroy_workqueue(ksmbd_wq);
		ksmbd_wq = NULL;
		return -ENOMEM;
	}

	attrs->nice = 15;

	get_online_cpus();
	(void)apply_workqueue_attrs(ksmbd_wq, attrs);
	free_workqueue_attrs(attrs);
	put_online_cpus();

	return 0;
}

void ksmbd_workqueue_destroy(void)
{
	destroy_workqueue(ksmbd_wq);
	ksmbd_wq = NULL;
}

bool ksmbd_queue_work(struct ksmbd_work *work)
{
	static unsigned int i;

	if (!is_cortex_a9)
		return queue_work(ksmbd_wq, &work->work);

	++i;
	if (i % 4 == 0)
		return queue_work_on(0, ksmbd_wq, &work->work);

	return queue_work_on(1, ksmbd_wq, &work->work);
}
